package org.halk.httpserver.entity;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.io.InputStream;

/**
 * 对请求进行封装
 *
 * @Author zhuhao
 * @Date 2022/5/26 17:26
 * @desc
 */
@Data
@NoArgsConstructor
public class Request {

    /**
     * 输入流
     */
    private InputStream inputStream;
    /**
     * 请求头
     */
    private String header;
    /**
     * 请求路径
     */
    private String uri;

    public Request(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    /**
     * 解析
     */
    public void parse() {
        //从socket读取字符
        final int BUFFER_SIZE = 2048;
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = 0;
        StringBuilder requestStringBuilder = new StringBuilder(BUFFER_SIZE);

        try {
            int i;
            while ((i = this.inputStream.read(buffer)) != -1) {
                for (int j = 0; j < i; j++) {
                    requestStringBuilder.append((char) buffer[j]);
                }
                bytesRead += i;
                // 如果读取的字节数小于缓冲区大小，说明可能已经读完了
                if (i < BUFFER_SIZE) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            bytesRead = -1;
        }

        System.out.println(requestStringBuilder);
        this.header = requestStringBuilder.toString();

        this.uri = this.parseUri(requestStringBuilder.toString());
    }

    /**
     * 解析路径中的参数
     *
     * @param requestString
     */
    private String parseUri(String requestString) {
        int index1 = requestString.indexOf(' ');
        if (index1 != -1) {
            int index2 = requestString.indexOf(' ', index1 + 1);
            if (index2 > index1) {
                return requestString.substring(index1 + 1, index2);
            }
        }
        return null;
    }

}
